<template>
  <!-- 面包屑导航 -->
    <div style="margin-top: 20px; margin-left: 20px">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item><b>我的课堂</b></el-breadcrumb-item>
            <el-breadcrumb-item  @click=" router.push('/classStart/teacherCourseInfo')">课程信息</el-breadcrumb-item>
            <el-breadcrumb-item>课程调整</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div style="display: flex">
        <div class="button-container" style="margin-top: 20px; margin-left: 20px">
            <el-button type="primary" @click="goAddCourse">
                添加课程<el-icon><CirclePlusFilled /></el-icon>
            </el-button>
        </div>
        <!-- 时间查询功能 -->
        <div style="margin-top: 20px; margin-left: 20px" >
            <el-form :model="queryForm" inline>
                <el-form-item label="搜索">
                    <el-input v-model="input" style="width: 240px" placeholder="请输入时间" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchCourses">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>

  <!-- 课程安排表格 -->
    <div class="table-container">
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="course" label="课程名" width="200px"/>
            <el-table-column prop="location" label="上课地点" width="200px"/>
            <el-table-column prop="startTime" label="开始时间" width="200px"/>
            <el-table-column prop="endTime" label="结束时间" width="200px"/>
            <el-table-column prop= "state" label="状态"  width="200px">
                <template #default="scope">
                    <el-button
                            :type="getButtonType(scope.row)"
                            :disabled="scope.row.state === 0 || scope.row.state === 1 ||scope.row.state === 2 ||scope.row.state === 3"
                            @click="handleSignIn(scope.row)"
                    >
                        {{ getButtonText(scope.row) }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button
                            type="primary"
                            :disabled="scope.row.state === 0 || scope.row.state === 3"
                            @click="handleUpdateCourse(scope.row)"
                    >
                        调整<el-icon class="el-icon--right"><ArrowRight /></el-icon>
                    </el-button>

                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页按钮 -->
    <div class="demo-pagination-block">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <!--  调整课程按钮对话框  -->
    <el-dialog v-model="tableEditVisible" title="课程调整" width="500">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">

            <el-form-item v-show="false" label="序号" prop="id">
                <el-input
                    v-model="form.id"
                    style="width: 240px"
                    disabled
                />
            </el-form-item>
            <el-form-item label="课程号" prop="courseNumber">

                    <el-input
                        v-model="form.courseNumber"
                        style="width: 240px"
                        disabled
                    />

            </el-form-item>
            <el-form-item label="课程名" prop="course">
                <el-input
                    v-model="form.course"
                    style="width: 240px"
                    disabled
                />
            </el-form-item>

            <el-form-item label="上课地点" prop="leaveType">
                <el-select v-model="form.location" placeholder="请选择上课地点" style="width: 200px;">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="起始时间" prop="startTime">
                <el-date-picker v-model="form.startTime"
                                type="datetime"
                                placeholder="请选择起始时间"
                                format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="form.endTime"
                                type="datetime"
                                placeholder="请选择结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--  添加课程按钮对话框  -->
    <el-dialog v-model="addCourseDialog" title="添加课程" width="500">
        <el-form :model="formb" :rules="rulesb" ref="formRefb" label-width="100px">

            <el-form-item label="课程号" prop="courseNumber">

                <el-input
                    v-model="formb.courseNumber"
                    style="width: 240px"
                    disabled
                />

            </el-form-item>
            <el-form-item label="课程名" prop="course">
                <el-input
                    v-model="formb.course"
                    style="width: 240px"
                    disabled
                />
            </el-form-item>

            <el-form-item label="上课地点" prop="leaveType">
                <el-select v-model="formb.location" placeholder="请选择上课地点" style="width: 200px;">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="起始时间" prop="startTime">
                <el-date-picker v-model="formb.startTime"
                                type="datetime"
                                placeholder="请选择起始时间"
                                format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="formb.endTime"
                                type="datetime"
                                placeholder="请选择结束时间"
                                format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelAdd">取消</el-button>
                <el-button type="primary" @click="confirmAdd">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import router from "../../../../router/index.js";
import {ArrowRight, CirclePlusFilled} from "@element-plus/icons-vue";


import {onMounted, ref} from "vue";
import request8090 from "../../../../utils/request8090.js";
import {ElMessage} from "element-plus";
import moment from "moment";

const tableData = ref([]);
onMounted(() => {
    getOneCourseInfo()
});

// 获取课程列表
const getOneCourseInfo = () => {
    request8090({
        url: '/teacher/getOneCourseInfo',
        method: 'GET',
        params: {
            currentPage: pagination.value.currentPage,
            size: pagination.value.pageSize,
            courseNumber: sessionStorage.getItem('courseNumber')
        },
    })
        .then(res => {
            if (res.data.errorCode === 200) {
                tableData.value = res.data.data.records;
                pagination.value.total = res.data.data.total;
            } else {
                ElMessage.error('获取数据失败');
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            ElMessage.error('请求失败');
        });

}
// 对话框取消添加按钮
const cancelAdd = () =>{
    formb.value.location = ''
    formb.value.startTime = ''
    formb.value.endTime = ''
    addCourseDialog.value = false
}
// 添加课程函数
const addCourse = () => {
    // 提交表单数据
    request8090({
        url: '/teacher/insertCourse',
        method: 'post',
        data: {
            courseNumber:formb.value.courseNumber,
            course:formb.value.course,
            teacherName: sessionStorage.getItem('name'),
            location:formb.value.location,
            startTime:moment(formb.value.startTime).format('YYYY-MM-DD HH:mm:ss'),
            endTime: moment(formb.value.endTime).format('YYYY-MM-DD HH:mm:ss'),
            teacherNumber:sessionStorage.getItem('teacherNumber')
        }
    })
        .then(res => {
            if (res.data.errorCode === 200) {
                ElMessage.success('提交成功');
                getOneCourseInfo();
                addCourseDialog.value = false;
                console.log("表单验证成功");
            } else {
                ElMessage.error('提交失败');
            }
        })
        .catch(error => {
            console.error('提交请求失败:', error);
            ElMessage.error('提交请求失败');
        });
}

// 添加课程按钮
const goAddCourse = () =>{
    addCourseDialog.value = true
    formb.value.courseNumber = sessionStorage.getItem('courseNumber')
    formb.value.course = sessionStorage.getItem('course')
}

const tableEditVisible= ref(false)
const addCourseDialog = ref(false)
//初始化的默认分页大小
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
});
//显示行数大小改变时刷新页面
const handleSizeChange = (size) => {
    pagination.value.pageSize = size;
    getOneCourseInfo();
}
//显示页数改变时刷新页面
const handleCurrentChange = (page) => {
    pagination.value.currentPage = page;
    getOneCourseInfo();
}
// 按钮的字体显示
const getButtonText = (row) => {
    if (row.state === 1) {
        return '正常';
    } else if (row.state === 0) {
        return '待审核';
    } else if (row.state === 2) {
        return '已拒绝';
    }else {
        return '调整中';
    }
}
//改变按钮状态
const getButtonType = (row) => {
    if (row.state === 1) {
        return 'success';
    } else if (row.state === 2) {
        return 'danger';
    } else if (row.state === 0) {
        return 'info';
    }else {
        return 'warning'
    }
}
const initialFormData = ref({}); // 存放初始数据

// 调整按钮
const handleUpdateCourse=(row)=>{

    tableEditVisible.value = true
    form.value.id = row.id
    form.value.courseNumber = row.courseNumber
    form.value.course = row.course
    form.value.location = row.location
    form.value.startTime = row.startTime
    form.value.endTime = row.endTime

    // 保存初始数据
    initialFormData.value = { ...form.value };
}
// 提交调整的数据
const form = ref({
    id: '',
    courseNumber: '',
    course: '',
    location: '',
    startTime: '',
    endTime: ''
})

// 提交调整的数据
const formb = ref({

    courseNumber: '',
    course: '',
    location: '',
    startTime: '',
    endTime: ''
})
// 取消提交
const reset = () =>{
    tableEditVisible.value = false
}
// 校验规则
const rules = {
    location: [{ required: true, message: "请选择上课地点", trigger: "change" }],
    startTime: [{ required: true, message: "请选择起始时间", trigger: "change" }],
    endTime: [
        { required: true, message: "请选择结束时间", trigger: "change" },
        {
            validator: (rule, value, callback) => {
                if (!value || !form.value.startTime) {
                    callback();
                } else {
                    const startTime = new Date(form.value.startTime);
                    const endTime = new Date(value);
                    const diffInHours = (endTime - startTime) / (1000 * 60 * 60);

                    if (endTime <= startTime) {
                        callback(new Error("结束时间不能在起始时间之前"));
                    } else if (diffInHours > 8) {
                        callback(new Error("课程时间不能超过8小时"));
                    } else {
                        callback();
                    }
                }
            },
            trigger: "change"
        }
    ]
};

const rulesb = {
    location: [{ required: true, message: "请选择上课地点", trigger: "change" }],
    startTime: [{ required: true, message: "请选择起始时间", trigger: "change" }],
    endTime: [
        { required: true, message: "请选择结束时间", trigger: "change" },
        {
            validator: (rule, value, callback) => {
                if (!value || !formb.value.startTime) {
                    callback();
                } else {
                    const startTime = new Date(formb.value.startTime);
                    const endTime = new Date(value);
                    const diffInHours = (endTime - startTime) / (1000 * 60 * 60);

                    if (endTime <= startTime) {
                        callback(new Error("结束时间不能在起始时间之前"));
                    } else if (diffInHours > 8) {
                        callback(new Error("课程时间不能超过8小时"));
                    } else {
                        callback();
                    }
                }
            },
            trigger: "change"
        }
    ]
};


// 调整课程表单确认修改按钮里的函数
const confirm = () =>{

    // 提交表单数据
    request8090({
        url: '/teacher/updatecourse',
        method: 'put',
        data: {
              id:form.value.id,
              courseNumber:form.value.courseNumber,
              course:form.value.course,
              location:form.value.location,
              startTime:moment(form.value.startTime).format('YYYY-MM-DD HH:mm:ss'),
              endTime: moment(form.value.endTime).format('YYYY-MM-DD HH:mm:ss')
        }
    })
        .then(res => {
            if (res.data.errorCode === 200) {
                ElMessage.success('提交成功');
                getOneCourseInfo();
                tableEditVisible.value = false;
                console.log("表单验证成功");
            } else {
                ElMessage.error('提交失败');
            }
        })
        .catch(error => {
            console.error('提交请求失败:', error);
            ElMessage.error('提交请求失败');
        });

}
const formRef = ref("formRef");

// 提交表单
const submitForm = () => {
    const isFormChanged = JSON.stringify(form.value) !== JSON.stringify(initialFormData.value);
    formRef.value.validate((valid) => {
        if (valid) {
            if(isFormChanged){
                confirm()
            }else {
                ElMessage.error('未做任何修改');
            }
        }
    });
};
const formRefb = ref("formRefb");
// 对话框确定添加按钮
const confirmAdd = () =>{
    formRefb.value.validate((valid) => {
        if (valid) {
            addCourse()
        }
    });
}

// 上课地点下拉框
const options = [
    {
        value: 'A001',
        label: 'A001',
    },
    {
        value: 'A002',
        label: 'A002',
    },
    {
        value: 'A003',
        label: 'A003',
    },
    {
        value: 'A004',
        label: 'A004',
    },
    {
        value: 'A005',
        label: 'A005',
    },
    {
        value: 'A101',
        label: 'A101',
    },
    {
        value: 'A102',
        label: 'A102',
    },
    {
        value: 'A103',
        label: 'A103',
    },
    {
        value: 'A104',
        label: 'A104',
    },
    {
        value: 'A105',
        label: 'A105',
    },
    {
        value: 'A201',
        label: 'A201',
    },
    {
        value: 'A202',
        label: 'A202',
    },
    {
        value: 'A203',
        label: 'A203',
    },
    {
        value: 'A204',
        label: 'A204',
    },
    {
        value: 'A205',
        label: 'A205',
    },
]



const input = ref(''); // 新增：存储搜索框的输入值

// 新增：搜索功能
const searchCourses = () => {
    request8090({
        url: '/teacher/getCourseByDate',
        method: 'GET',
        params: {
            courseNumber: sessionStorage.getItem('courseNumber'), // 获取课程编号
            time: input.value, // 获取输入框中的搜索时间
            currentPage: pagination.value.currentPage, // 当前页码
            size: pagination.value.pageSize // 分页大小
        }
    })
        .then(res => {
            if (res.data.errorCode === 200) {
                tableData.value = res.data.data.records; // 更新表格数据
                pagination.value.total = res.data.data.total; // 更新总数
                input.value=''
            } else {
                ElMessage.error('获取数据失败');
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            ElMessage.error('请求失败');
        });
};


</script>

<style scoped>

</style>